import { createChannel, createClientFactory, FetchTransport, CallOptions, ClientMiddleware } from "nice-grpc-web";
import { LLMServiceDefinition } from "@/types/proto/api/v1/llm_service";
import { GranaryServiceDefinition } from "@/types/proto/api/v1/granary_service";
import { WorkflowServiceDefinition } from "@/types/proto/api/v1/workflow_service";
import { ExchangeServiceDefinition } from "@/types/proto/api/v1/exchange_service";
import { ResourceServiceDefinition } from "@/types/proto/api/v1/resource_service";
import { UserServiceDefinition } from "@/types/proto/api/v1/user_service";
import { AuthServiceDefinition } from "@/types/proto/api/v1/auth_service";
import { SubjectServiceDefinition } from "@/types/proto/api/v1/subject_service";
import { KnotServiceDefinition } from "@/types/proto/api/v1/knot_service";
import { HelloServiceDefinition } from "@/types/proto/api/v1/hello_service";


import {useUserStore} from "@/store/user"

const channel = createChannel(
  window.location.origin,
  FetchTransport({
    credentials: "include",
  }),
);

const authMiddleware: ClientMiddleware = async function* (call, options: CallOptions) {
  const store = useUserStore();
  try {
    return yield* call.next(call.request, {
      ...options,
      metadata: store.getHeaderToken(),
    });
  } catch (error:any) {
    console.log("error info:", error)
    if (error.code === 16) { // 16 是 UNAUTHENTICATED 的 gRPC 状态码
      // 处理 token 过期的情况
      store.token = undefined
      window.location.href = '/signin';
    }
  }
};

const clientFactory = createClientFactory().use(authMiddleware);
export const llmServiceClient = clientFactory.create(LLMServiceDefinition, channel);
export const granaryServiceClient = clientFactory.create(GranaryServiceDefinition, channel);
export const workflowServiceClient = clientFactory.create(WorkflowServiceDefinition, channel);
export const exchangeServiceClient = clientFactory.create(ExchangeServiceDefinition, channel);
export const resourceServiceClient = clientFactory.create(ResourceServiceDefinition, channel);
export const userServiceClient = clientFactory.create(UserServiceDefinition, channel);
export const authServiceClient = clientFactory.create(AuthServiceDefinition, channel);
export const subjectServiceClient = clientFactory.create(SubjectServiceDefinition, channel);
export const knotServiceClient = clientFactory.create(KnotServiceDefinition, channel);
export const helloServiceClient = clientFactory.create(HelloServiceDefinition, channel);
